<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/8/6
 * Time: 14:40
 */
namespace App\Http\Controllers\Api\Notify;

use App\Http\Controllers\Controller;
use App\Repositories\CollectMoneyBillRepository;
use App\Repositories\PersonalAccountWithdrawRepository;
use App\Repositories\RepaymentAccountWithdrawRepository;
use App\Repositories\RepaymentPlanConsumeRepository;
use App\Repositories\RepaymentPlanFailHandlersRepository;
use App\Repositories\RepaymentPlanRepository;
use App\Repositories\ThreeApiErrorLogsRepository;
use App\Repositories\UserCreditCardRepository;
use App\Repositories\UserPassageRegisterRepository;
use App\Repositories\UserRepository;
use App\Services\CollectMoneyProfitService;
use App\Services\MessageService;
use App\Services\RepaymentProfitService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class LargePayXNotifyController extends Controller
{
    protected $threeApiErrorLogsRepository;
    protected $repaymentProfitService;
    protected $repaymentAccountWithdrawRepository;
    protected $personalAccountWithdrawRepository;
    protected $userRepository;
    protected $userCreditCardRepository;
    protected $repaymentPlanFailHandlersRepository;
    protected $messageService;
    protected $apiKey;

    public function __construct(ThreeApiErrorLogsRepository $threeApiErrorLogsRepository,
                                RepaymentProfitService $repaymentProfitService,
                                RepaymentAccountWithdrawRepository $repaymentAccountWithdrawRepository,
                                PersonalAccountWithdrawRepository $personalAccountWithdrawRepository,
                                UserRepository $userRepository,
                                UserCreditCardRepository $userCreditCardRepository,
                                RepaymentPlanFailHandlersRepository $repaymentPlanFailHandlersRepository,
                                MessageService $messageService)
    {
        $this->threeApiErrorLogsRepository = $threeApiErrorLogsRepository;
        $this->repaymentProfitService = $repaymentProfitService;
        $this->repaymentAccountWithdrawRepository = $repaymentAccountWithdrawRepository;
        $this->personalAccountWithdrawRepository = $personalAccountWithdrawRepository;
        $this->userRepository = $userRepository;
        $this->userCreditCardRepository = $userCreditCardRepository;
        $this->repaymentPlanFailHandlersRepository = $repaymentPlanFailHandlersRepository;
        $this->messageService = $messageService;
        $this->apiKey = config('pay.fourpay.api_key');
    }

    /**
     * 消费回调
     * {
     * "sign": "7aca35d53b14e4e4af07fa984cc09181",
     * "message": "支付成功",
     * "amount": "20.00",
     * "dsorderid": "A821456714614513",
     * "subMerBalance": "23.06",
     * "code": "SUCCESS"
     * }
     *  {"sign":"7aca35d53b14e4e4af07fa984cc09181","message":"\u652f\u4ed8\u6210\u529f","amount":"20.00","dsorderid":"A821456714614513","subMerBalance":"23.06","code":"SUCCESS"}
     */
    public function trade(Request $request)
    {
        Log::info('consumeNotifyC:' . json_encode($request->all()));
        $param = $request->all();
        $sign = $param['sign'];
        unset($param['sign']);
        if ($sign != getSign($param, $this->apiKey)) {
            Log::info('大额还款X交易回调签名验证不正确');
            die('大额还款X交易回调签名验证不正确');
        }
        $repaymentPlanConsumeRepository = new RepaymentPlanConsumeRepository();
        $consume = $repaymentPlanConsumeRepository->byConsumeSn($param['mch_no']);
        $repaymentPlan = new RepaymentPlanRepository();
        $plan = $repaymentPlan->byId($consume->repayment_plan_id);
        //更新消费状态
        if ($param['order_status'] == 'SUCCESS') {
            $repaymentPlanConsumeRepository->updateStatusByConsumeSn($param['mch_no'], 2002);//成功
            //发送消费成功消息提醒
            $userOwn = $this->userRepository->byId($plan->user_id);
            $creditCard = $this->userCreditCardRepository->isExistUserBankNo($plan->user_id, $consume->bank_no);
            $this->messageService->messageTemplate(17, $userOwn->invited_code, $creditCard->bank_no, $creditCard->bank_description,
                $consume->consume_money, '', '', $consume->repayment_plan_id, '', '');
            $this->repaymentProfitService->profit($param['mch_no'], $consume->consume_money, $consume->consume_service_charge,
                $consume->consume_passage_id, $plan->user_id, $creditCard->bank_code, $userOwn->mobile);
        } else {
            $message = isset($param['fail_message']) ? $param['fail_message'] : '';
            $repaymentPlanConsumeRepository->updateStatusByConsumeSn($param['mch_no'], 2003, $message);//失败
            if (date('Y-m-d') == date('Y-m-d', $consume->consume_time)) {
                $plan->update(['repayment_plan_status' => 1005, 'update_plan_time' => time()]);
            }
            //发送消费失败消息提醒
            $userOwn = $this->userRepository->byId($plan->user_id);
            $creditCard = $this->userCreditCardRepository->isExistUserBankNo($plan->user_id, $consume->bank_no);
            $this->messageService->messageTemplate(16, $userOwn->invited_code, $creditCard->bank_no, $creditCard->bank_description,
                $consume->consume_money, '', '', $consume->repayment_plan_id, '', '');
        }
        $errorData = [
            'order_no' => $param['mch_no'],
            'error_code' => $param['order_status'],
            'error_msg' => json_encode($request->all()),
            'api_type' => 18
        ];
        $this->threeApiErrorLogsRepository->create($errorData);
        echo 'SUCCESS';
    }

    /**
     * 还款回调
     */
    public function withdraw(Request $request)
    {
        Log::info('repaymentNotifyC:' . json_encode($request->all()));
        $param = $request->all();
        $sign = $param['sign'];
        unset($param['sign']);
        if ($sign != getSign($param, $this->apiKey)) {
            Log::info('大额还款X提现回调签名验证不正确');
            die('大额还款X提现回调签名验证不正确');
        }
        $this->repaymentProfitService->repaymentE($request);
    }

    /**
     * 提现回调
     */
    public function withdrawHandle(Request $request)
    {
        Log::info('withdrawNotifyC:' . json_encode($request->all()));
        $param = $request->all();
        $sign = $param['sign'];
        unset($param['sign']);
        if ($sign != getSign($param, $this->apiKey)) {
            Log::info('大额还款X提现回调签名验证不正确');
            die('大额还款X提现回调签名验证不正确');
        }
        $withdraw = $this->repaymentAccountWithdrawRepository->byWithdrawNo($param['mch_no']);
        //更新还款提现状态
        if ($param['order_status'] == 'SUCCESS') {
            $this->repaymentAccountWithdrawRepository->updateStatusByWithdrawNo($param['mch_no'], 4002);//成功
            echo 'SUCCESS';
            //提现成功失败消息提醒
            $userOwn = $this->userRepository->byId($withdraw->user_id);
            $this->messageService->messageTemplate(18, $userOwn->invited_code, $withdraw->bank_no, $withdraw->bank_description,
                $withdraw->withdraw_money, '', '', 0, '', '');
        } else {
            $this->repaymentAccountWithdrawRepository->updateStatusByWithdrawNo($param['mch_no'], 4003);//失败
            $data['withdraw_status'] = 4003;
            $data['fail_message'] = $param['fail_message'];
            Log::info('自动处理进入手动处理');
            $creditCard = $this->userCreditCardRepository->byId($withdraw->credit_card_id);
            //自动处理进入手动处理
            $data = [
                'fail_repayment_sn' => $withdraw->withdraw_no,
                'repayment_plan_id' => $withdraw->repayment_plan_id,
                'plan_repayment_id' => $withdraw->plan_repayment_id,
                'user_id' => $withdraw->user_id,
                'credit_card_id' => $withdraw->credit_card_id,
                'repayment_passage_id' => $withdraw->passage_id,
                'repayment_money' => $withdraw->withdraw_money,
                'sub_merchant_no' => $withdraw->sub_merchant_no,
                'bank_no' => $withdraw->bank_no,
                'bank_mobile' => $creditCard->bank_mobile,
                'api_result' => json_encode($request->all()),
                'create_time' => time(),
            ];
            $this->repaymentPlanFailHandlersRepository->create($data);
        }
        $errorData = [
            'order_no' => $param['mch_no'],
            'error_code' => $param['order_status'],
            'error_msg' => json_encode($request->all()),
            'api_type' => 28
        ];
        $this->threeApiErrorLogsRepository->create($errorData);
    }
}